package net.dipper.tankwar.game.control;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import net.dipper.tankwar.core.data.ObjectMap;
import net.dipper.tankwar.core.helper.Position;
import net.dipper.tankwar.game.helper.Message;
import net.dipper.tankwar.game.helper.MessageManager;
import net.dipper.tankwar.game.ui.GameContext;
import wnb.util.config.ConfigurationManager;
import wnb.util.control.Command;
import wnb.util.helper.ArrayHelper;

public class CalcResultCommand extends Command {
	private GameContext context;
	private ObjectMap map;
	
	public CalcResultCommand(GameContext context, ObjectMap map){
		this.context = context;
		this.map = map;
	}

	@Override
	public void exec() {	
		try {
			byte result = calcResult(map);
			Message message = new Message(Message.GAME_RESULT, 0, 0, -1, Byte.toString(result));
			MessageManager manager = MessageManager.getInstance();
			manager.push(message);
			
			if(result == GameRule.RESULT_FAIL || result == GameRule.RESULT_SUCCESS){
				this.context.stop();
			}
		} catch (ParserConfigurationException | SAXException | IOException e) {
			e.printStackTrace();
		}
	}
	
	private byte calcResult(ObjectMap map) throws ParserConfigurationException, SAXException, IOException{
		Position player = map.getPlayer();
		
		//计算是否还存在目标
		boolean hasTarget = false;
		String strTargetVal = ConfigurationManager.getAppSetting("target_value");
		byte targetVal = Byte.parseByte(strTargetVal);
		int width = map.getWidth();
		int height = map.getHeight();
		for(int i=0;i<width;i++){
			for(int j=0;j<height;j++){
				byte value = map.getObject(i, j);
				if(value == targetVal){
					hasTarget = true;
					break;
				}
			}
			
			if(hasTarget)
				break;
		}
		
		if(hasTarget == false)
			return GameRule.RESULT_FAIL;
		
		//计算是否玩家是否还存在
		byte playerVal = map.getObject(player.x, player.y);
		if(playerVal == 0)
			return GameRule.RESULT_FAIL;
		
		//计算是否还存在敌对势力
		boolean hasEnemy = false;
		String strEnemyVal = ConfigurationManager.getAppSetting("enemy_value");
		String[] arrEnemyVal = strEnemyVal.split(",");
		for(int i=0; i<width; i ++){
			for(int j=0; j<height; j++){
				if(i == player.x && j == player.y)
					continue;
				
				byte value = map.getObject(i, j);
				if(-1 != ArrayHelper.index(arrEnemyVal, Byte.toString(value))){
					hasEnemy = true;
					continue;
				}
			}
		}
		
		if(hasEnemy)
			return GameRule.RESULT_CONTINUE;
		
		return GameRule.RESULT_SUCCESS;
	}
}
